import serial, serial.tools.list_ports

baudrate = 9600
received_data = ''

def getAvailableComPorts():
	acp = list()
	temp = serial.tools.list_ports.comports()	
	for a in temp:
		acp.append(a.device)
		#acp.append(a.description)
	return acp

def readData():
	received_data = ''
	while True:
		try:
			temp1 = ser.read()
		except:
			break
		temp2 = b''
		try:
			temp3 = temp1.decode('ascii')
		except:
			temp2 = temp1
			try:
				temp2 += ser.read()
			except:
				break
			temp3 = temp2.decode('ascii')

		if temp3 == '\n':
			break
		else :
			received_data += temp3
		print(received_data)
	return received_data

def setComPort(port, baudrate):
	ser.port = port
	ser.baudrate = baudrate

def writeData(string):
	if not isSerialPortOpen():
		return False
	byte = string.encode('GB18030')
	ser.write(byte)
	byte_return = '\n'.encode('GB18030')
	ser.write(byte_return)

def openSerialPort():
	ser.open()

def closeSerialPort():
	ser.close()

def isSerialPortOpen():
	return ser.is_open

def setSerialParity(choice_parity):
	if choice_parity == 0:
		ser.parity = serial.PARITY_NONE
	elif choice_parity == 1:
		ser.parity = serial.PARITY_EVEN
	else:
		ser.parity = serial.PARITY_ODD

ser = serial.Serial()
if __name__ == '__main__':
	acp = getAvailableComPorts()
	ser = serial.Serial()
	setComPort(acp[0], baudrate)
	ser.open()
	data_to_write = input('Please input string to send:\n')
	writeData(data_to_write)
	received_data = readData()
	print(received_data)
	ser.close()